package com.ruoyi.system.controller;


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.dfp.DfpField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.ElectricRate;
import com.ruoyi.system.domain.TExternalPowerSupply;
import com.ruoyi.system.domain.TOutageFeedback;
import com.ruoyi.system.domain.TTingdianTuifu;
import com.ruoyi.system.service.ITExternalPowerSupplyService;
import com.ruoyi.system.service.ITOutageFeedbackService;
import com.ruoyi.system.service.ITTingdianTuifuService;
import com.ruoyi.system.utils.TransData;

/**
 * 发电及时率报表
 * 
 * @author ruoyi
 * @date 2021-12-10
 */
@RestController
@RequestMapping("/tietasystem/tstatistics")
public class TStatisticsController extends BaseController
{
	// 停电且退服
    @Autowired
    private ITTingdianTuifuService tTingdianTuifuService;
    // 停电反馈数据
    @Autowired
    private ITOutageFeedbackService tOutageFeedbackService;
    // 外部供电退服
    @Autowired
    private ITExternalPowerSupplyService tExternalPowerSupplyService;
    
    static List<String> areaNames = new ArrayList<>(Arrays.asList("沈阳", "大连", "鞍山", "抚顺", "本溪", "丹东", "锦州", "营口", "阜新", "辽阳", "盘锦", "铁岭", "朝阳", "葫芦岛"));

    /**
     * 发电及时率报表列表
     */
    @PreAuthorize("@ss.hasPermi('tietasystem:tstatistics:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElectricRate electricRate){
    	
    	//停电且退服
    	TTingdianTuifu ting = new TTingdianTuifu();
    	ting.setVersion(electricRate.getVersion());
    	List<TTingdianTuifu> tinglist = tTingdianTuifuService.selectTTingdianTuifuList(ting);
    	//停电反馈
    	TOutageFeedback feed = new TOutageFeedback();
    	feed.setVersion(electricRate.getVersion());
    	List<TOutageFeedback> feedlist = tOutageFeedbackService.selectTOutageFeedbackList(feed);
    	//外部供电
    	TExternalPowerSupply exter = new TExternalPowerSupply();
    	exter.setVersion(electricRate.getVersion());
    	List<TExternalPowerSupply> exterlist = tExternalPowerSupplyService.selectTExternalPowerSupplyList(exter);

    	String depName = getLoginUser().getUser().getDept().getDeptName();
    	 //String depName = "辽宁省";
    	String userName = getLoginUser().getUser().getUserName();
    	 //String userName = "admin";
    	String city = ("辽宁省".equals(TransData.transCityMap(depName)) || "admin".equals(userName)) ? null : TransData.transCityMap(depName);

    	List<ElectricRate> rateList = Lists.newArrayList();
    	for(String name : areaNames){
    		if(city == null || name.equals(city)){
    			ElectricRate bean = new ElectricRate();
    			// 停电数量（有需求）
    			Long t1 = feedlist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "是".equals(f.getIsneedElectricity())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 外部供电退服无停电告警（有需求）
    			Long t2 = exterlist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "是".equals(f.getIsneedElectricity())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 外部供电退服无停电告警（无需求无证明）
    			Long t3 = exterlist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "否".equals(f.getIsneedElectricity()) && "否".equals(f.getIsOperator())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 停电且退服（有需求）
    			Long t4 = tinglist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "是".equals(f.getIsneedFaidtian())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 外部供电退服无停电告警（有需求）
    			Long t5 = exterlist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "是".equals(f.getIsneedElectricity())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 停电且退服（无需求无证明）
    			Long t6 = tinglist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "否".equals(f.getIsneedFaidtian()) && "否".equals(f.getIsNoFadian())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 外部供电退服无停电告警（无需求无证明）
    			Long t7 = exterlist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "否".equals(f.getIsneedElectricity()) && "否".equals(f.getIsOperator())){
    					return true;
    				}
    				return false;
    			}).count();

    			bean.setCityName(name);
    			bean.setToutageHasNums_b(t1);
    			bean.setTexternalHasNums_b(t2);
    			bean.setTexternalNoNums_b(t3);
    			bean.setTtingHasNums_y(t4);
    			bean.setTexternalHasNums_y(t5);
    			bean.setTtingNoNums_y(t6);
    			bean.setTexternalNoNums_y(t7);
    			Long bTotle = t1 + t2 + t3;
    			bean.setBtotal(bTotle);
    			Long yTotle = t4 + t5 + t6 + t7;
    			bean.setYtotal(yTotle);
    			if(bTotle == 0){
    				bean.setRate("0%");
    			} else {
    				BigDecimal a1 = new BigDecimal(bTotle.doubleValue());
        			BigDecimal b1 = new BigDecimal(yTotle.doubleValue());
        			BigDecimal c = new BigDecimal(String.valueOf(100));
        			BigDecimal e = new BigDecimal(String.valueOf(1));
        			Double rate = (e.subtract(b1.divide(a1, 4, RoundingMode.HALF_UP))).multiply(c).doubleValue();
        			bean.setRate(rate + "%");
    			}
    			rateList.add(bean);
    		}
    	}

    	//总数
    	Long total1 = 0L;
    	Long total2 = 0L;
    	Long total3 = 0L;
    	Long total4 = 0L;
    	Long total5 = 0L;
    	Long total6 = 0L;
    	Long total7 = 0L;
    	Long total8 = 0L;
    	Long total9 = 0L;
    	for(ElectricRate el : rateList){
    		total1 = total1 + el.getToutageHasNums_b();
    		total2 = total2 + el.getTexternalHasNums_b();
    		total3 = total3 + el.getTexternalNoNums_b();
    		total4 = total4 + el.getTtingHasNums_y();
    		total5 = total5 + el.getTexternalHasNums_y();
    		total6 = total6 + el.getTtingNoNums_y();
    		total7 = total7 + el.getTexternalNoNums_y();
    		total8 = total8 + el.getBtotal();
    		total9 = total9 + el.getYtotal();
    	}
    	ElectricRate totalBean = new ElectricRate();
    	totalBean.setCityName("总计");
    	totalBean.setToutageHasNums_b(total1);
    	totalBean.setTexternalHasNums_b(total2);
    	totalBean.setTexternalNoNums_b(total3);
    	totalBean.setTtingHasNums_y(total4);
    	totalBean.setTexternalHasNums_y(total5);
    	totalBean.setTtingNoNums_y(total6);
    	totalBean.setTexternalNoNums_y(total7);
    	totalBean.setBtotal(total8);
    	totalBean.setYtotal(total9);
    	if(total8 == 0){
    		totalBean.setRate("0%");
    	} else {
    		BigDecimal a1 = new BigDecimal(total8.doubleValue());
    		BigDecimal b1 = new BigDecimal(total9.doubleValue());
    		BigDecimal c = new BigDecimal(String.valueOf(100));
    		BigDecimal e = new BigDecimal(String.valueOf(1));
			Double rate = (e.subtract(b1.divide(a1, 4, BigDecimal.ROUND_HALF_UP))).multiply(c).doubleValue();
    		totalBean.setRate(rate + "%");
    	}

		rateList.add(totalBean);

        return getDataTable(rateList);
    }

    /**
     * 导出停电且退服（测试一下，确认后删除此注释）列表
     */
    @PreAuthorize("@ss.hasPermi('tietasystem:tstatistics:export')")
    @Log(title = "发电及时率", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ElectricRate electricRate) {

    	//停电且退服
    	TTingdianTuifu ting = new TTingdianTuifu();
    	ting.setVersion(electricRate.getVersion());
    	List<TTingdianTuifu> tinglist = tTingdianTuifuService.selectTTingdianTuifuList(ting);
    	//停电反馈
    	TOutageFeedback feed = new TOutageFeedback();
    	feed.setVersion(electricRate.getVersion());
    	List<TOutageFeedback> feedlist = tOutageFeedbackService.selectTOutageFeedbackList(feed);
    	//外部供电
    	TExternalPowerSupply exter = new TExternalPowerSupply();
    	exter.setVersion(electricRate.getVersion());
    	List<TExternalPowerSupply> exterlist = tExternalPowerSupplyService.selectTExternalPowerSupplyList(exter);

    	String depName = getLoginUser().getUser().getDept().getDeptName();
    	 //String depName = "大连分公司";
    	String userName = getLoginUser().getUser().getUserName();
    	 //String userName = "dl";
    	String city = ("辽宁省".equals(TransData.transCityMap(depName)) || "admin".equals(userName)) ? null : TransData.transCityMap(depName);

    	List<ElectricRate> rateList = Lists.newArrayList();
    	for(String name : areaNames){
    		if(city == null || name.equals(city)){
    			ElectricRate bean = new ElectricRate();
    			// 停电数量（有需求）
    			Long t1 = feedlist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "是".equals(f.getIsneedElectricity())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 外部供电退服无停电告警（有需求）
    			Long t2 = exterlist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "是".equals(f.getIsneedElectricity())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 外部供电退服无停电告警（无需求无证明）
    			Long t3 = exterlist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "否".equals(f.getIsneedElectricity()) && "否".equals(f.getIsOperator())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 停电且退服（有需求）
    			Long t4 = tinglist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "是".equals(f.getIsneedFaidtian())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 外部供电退服无停电告警（有需求）
    			Long t5 = exterlist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "是".equals(f.getIsneedElectricity())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 停电且退服（无需求无证明）
    			Long t6 = tinglist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "否".equals(f.getIsneedFaidtian()) && "否".equals(f.getIsNoFadian())){
    					return true;
    				}
    				return false;
    			}).count();
    			// 外部供电退服无停电告警（无需求无证明）
    			Long t7 = exterlist.stream().filter(f -> {
    				if(name.equals(f.getCity()) && "否".equals(f.getIsneedElectricity()) && "否".equals(f.getIsOperator())){
    					return true;
    				}
    				return false;
    			}).count();
    			
    			bean.setCityName(name);
    			bean.setToutageHasNums_b(t1);
    			bean.setTexternalHasNums_b(t2);
    			bean.setTexternalNoNums_b(t3);
    			bean.setTtingHasNums_y(t4);
    			bean.setTexternalHasNums_y(t5);
    			bean.setTtingNoNums_y(t6);
    			bean.setTexternalNoNums_y(t7);
    			Long bTotle = t1 + t2 + t3;
    			bean.setBtotal(bTotle);
    			Long yTotle = t4 + t5 + t6 + t7;
    			bean.setYtotal(yTotle);
    			if(bTotle == 0){
    				bean.setRate("0%"); 
    			} else {
    				BigDecimal a1 = new BigDecimal(bTotle.doubleValue()); 
        			BigDecimal b1 = new BigDecimal(yTotle.doubleValue()); 
        			BigDecimal c = new BigDecimal(String.valueOf(100));
        			BigDecimal e = new BigDecimal(String.valueOf(1));
        			Double rate = (e.subtract(b1.divide(a1, 4, RoundingMode.HALF_UP))).multiply(c).doubleValue();
        			bean.setRate(rate + "%"); 
    			}
    			rateList.add(bean);
    		}
    	}
    	
    	//总数
    	Long total1 = 0L;
    	Long total2 = 0L;
    	Long total3 = 0L;
    	Long total4 = 0L;
    	Long total5 = 0L;
    	Long total6 = 0L;
    	Long total7 = 0L;
    	Long total8 = 0L;
    	Long total9 = 0L;
    	for(ElectricRate el : rateList){
    		total1 = total1 + el.getToutageHasNums_b();
    		total2 = total2 + el.getTexternalHasNums_b();
    		total3 = total3 + el.getTexternalNoNums_b();
    		total4 = total4 + el.getTtingHasNums_y();
    		total5 = total5 + el.getTexternalHasNums_y();
    		total6 = total6 + el.getTtingNoNums_y();
    		total7 = total7 + el.getTexternalNoNums_y();
    		total8 = total8 + el.getBtotal();
    		total9 = total9 + el.getYtotal();
    	}
    	ElectricRate totalBean = new ElectricRate();
    	totalBean.setCityName("总计");
    	totalBean.setToutageHasNums_b(total1);
    	totalBean.setTexternalHasNums_b(total2);
    	totalBean.setTexternalNoNums_b(total3);
    	totalBean.setTtingHasNums_y(total4);
    	totalBean.setTexternalHasNums_y(total5);
    	totalBean.setTtingNoNums_y(total6);
    	totalBean.setTexternalNoNums_y(total7);
    	totalBean.setBtotal(total8);
    	totalBean.setYtotal(total9);
    	if(total8 == 0){
    		totalBean.setRate("0%");
    	} else {
    		BigDecimal a1 = new BigDecimal(total8.doubleValue()); 
    		BigDecimal b1 = new BigDecimal(total9.doubleValue()); 
    		BigDecimal c = new BigDecimal(String.valueOf(100));
    		BigDecimal e = new BigDecimal(String.valueOf(1));
			Double rate = (e.subtract(b1.divide(a1, 4, RoundingMode.HALF_UP))).multiply(c).doubleValue();
    		totalBean.setRate(rate + "%");
    	}
		
		rateList.add(totalBean);
		
		ExcelUtil<ElectricRate> util = new ExcelUtil<ElectricRate>(ElectricRate.class);
        return util.exportExcel(rateList, "发电及时率");
    }


}
